import { routerRedux } from 'dva/router'
import * as menuService from 'services/menu'
import { signIn } from 'services/login';
import { userinfo} from 'services/user';

export default {
  namespace: 'login',
  state: {
    loginLoading: false,
  },
  subscriptions: {
    setup ({ dispatch, history }) {
      history.listen((location) => {

      })
    },
  },
  effects: {
    * login ({payload,}, { put, call,select }) {
      yield put({ type: 'showLoginLoading' });
      var data = {}
      try{
         data = yield call(signIn, payload);
      }catch(e){
        const msg = JSON.parse(e.message).msg
        yield put({ type: 'hideLoginLoading' });
        throw new Error(JSON.stringify({msg}))
      }
      const { locationQuery } = yield select(_ => _.app)
      if (data.success) {
        const { expire, token } = data
        const from = locationQuery;
        sessionStorage.setItem('expire', expire)
        sessionStorage.setItem('token', token)
        //const dataNav = yield call(menuService.queryNav,{ token });
        //sessionStorage.setItem('defaultPage',dataNav.menuList[0].url)
        const userInfo = yield call(userinfo);
        if(userInfo.code === 0) {
          delete userInfo.user.password;
          sessionStorage.setItem('userId',userInfo.user.userId);
          sessionStorage.setItem('yct_userinfo', JSON.stringify(userInfo.user));
        }
        yield put({ type: 'hideLoginLoading' });
        yield put({ type: 'app/query' })
      
        if (from) {
          yield put(routerRedux.push(from))
          // window.location.Reload()
        } else {
          // yield put(routerRedux.push('/dashboard'))
          yield put(routerRedux.push(sessionStorage.getItem('defaultPage')))
          // window.location.Reload()
        }
        window.location.reload(true)
      } else {
        yield put({ type: 'reload' });
        throw data
      }
      }
  },
  reducers: {
    reload (state) {
      return {
        ...state,
      }
    },
    showLoginLoading (state) {
      return {
        ...state,
        loginLoading: true,
      }
    },
    hideLoginLoading (state) {
      return {
        ...state,
        loginLoading: false,
      }
    },
  },
}
